/**
 * 作者:李杰
 * email: maillijie@gmail.com
 */
package com.javainfo.actions;

import java.util.List;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.rest.DefaultHttpHeaders;
import org.apache.struts2.rest.HttpHeaders;

import com.javainfo.entity.User;
import com.javainfo.util.Const;
import com.javainfo.util.JavaInfoActionSupport;
import com.opensymphony.xwork2.validator.annotations.RequiredStringValidator;
import com.opensymphony.xwork2.validator.annotations.Validations;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;

@SuppressWarnings("unchecked")
public class UserCtrl extends JavaInfoActionSupport {

	/** serialVersionUID */
	private static final long serialVersionUID = 1L;

	public String index() throws Exception {
		return INDEX;
	}
	
	/**
	 * 转向登录页面
	 * 
	 * @return
	 */
	public String unLogin() {
		setViewHistory();
		return "goToLogin";
	}

	/**
	 * 用户登录
	 * 
	 * @return
	 */
	@Action(value = "/user/login", results = { @Result(name = "index", location = "/login.jsp") })
	@Validations(requiredStrings = { @RequiredStringValidator(type = ValidatorType.SIMPLE, fieldName = "userAccount", message = "角色名称不能为空") })
	public HttpHeaders login() {
		User user = getServiceFactory().getUserService().checkUser(
				getRequest().getParameter("userAccount"),
				getRequest().getParameter("passwd"));
		if (user == null) {
			addActionMessage(getText(Const.Message.UNKNOWN_USER));
			return new DefaultHttpHeaders("goToLogin");
		} else {
			String last_url = getSession().get(Const.LAST_VIEW) == null ? "/category"
					: (String) getSession().get(Const.LAST_VIEW);
			getSession().put(Const.LOGIN_INFO, user);
			return urlForward(last_url);
		}
	}

	/**
	 * 用户退出
	 * 
	 * @return
	 */
	public HttpHeaders logout() {
		setViewHistory();
		String last_url = getSession().get(Const.LAST_VIEW) == null ? "/category"
				: (String) getSession().get(Const.LAST_VIEW);
		getSession().remove(Const.LOGIN_INFO);
		getSession().remove(Const.VIEW_HISTORY);
		getSession().remove(Const.LAST_VIEW);
		getSession().remove(Const.ARTICLE_IDS);
		return urlForward(last_url);
		// return SUCCESS;
	}

	/**
	 * 设置用户访问历史
	 */
	private void setViewHistory() {
		if (getSession().get(Const.VIEW_HISTORY) != null) {
			List<String> viewHistory = (List<String>) getSession().get(
					Const.VIEW_HISTORY);
			for (String url : viewHistory) {
				if (url.indexOf("unLogin") < 0 && url.indexOf("fckeditor") < 0
						&& url.indexOf("logout") < 0) {
					getSession().put(Const.LAST_VIEW, url);
				}
			}
		}
		if (getSession().get(Const.VIEW_HISTORY) == null) {
			getSession().put(Const.LAST_VIEW, "/category");
		}
	}
}
